package com.losdun.product.manage;

import com.alibaba.fastjson2.JSON;
import com.losdun.product.controller.req.CalPriceReq;
import com.losdun.product.domain.AttributeParts;
import com.losdun.product.domain.ProdPrice;
import com.losdun.product.domain.Product;
import com.losdun.product.domain.vo.ProductPriceVo;
import com.losdun.product.domain.vo.SkuVo;
import com.losdun.product.service.AttributePartsService;
import com.losdun.product.service.IProductService;
import com.losdun.product.service.ProdPriceService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author sword.ye
 * @date 2025/6/7
 **/
@Component
public class ProductPriceCalManage {
    public static final String SMALL_DOOR_UNIT_AREA = "3";
    @Autowired
    private IProductService productService;
    @Autowired
    private AttributePartsService attributePartsService;

    @Autowired
    private ProdPriceService prodPriceService;

    public ProductPriceVo calProductPrice(CalPriceReq req) throws Exception {
        //费用对象
        ProductPriceVo priceVo=new ProductPriceVo();
        Product product = productService.selectProductById(req.getProductId());
        if(product==null) {
            throw new RuntimeException("产品不存在!");
        }
        //开门方式对应的可选配件
        List<AttributeParts> attrParts = attributePartsService.queryAttributeParts(req.getOpenTypeId());
        //面积
        BigDecimal doorArea = this.getArea(attrParts.get(0),req.getDoorWidth(), req.getDoorHeight());

        //开门方式
        priceVo.setProductId(product.getId());
        priceVo.setProductName(product.getName());
        priceVo.setCustomerName(req.getCustomerName());
        priceVo.setProductCategoryName(product.getCategoryName());
        priceVo.setDoorArea(doorArea);
        priceVo.setOpenType(req.getOpenTypeName());
        //产品费用 颜色定制
        SkuVo skuVo=null;
        String sku=req.getOpenTypeId().toString();
        if(req.getColorId().equals(-1L)){
            priceVo.setColorName(req.getColorName());
            priceVo.setColorPrice(product.getColorCustomPrice());
            skuVo = this.getSkuVo(product.getSkus(), sku, true);
        }else{
            sku+="-"+req.getColorId();
            priceVo.setColorName(req.getColorName());
            skuVo=this.getSkuVo(product.getSkus(),sku,false);
        }
        if(skuVo==null){
            throw new RuntimeException("产品未找到!");
        }
        //小门
        if(req.getOpenTypeId().equals(19L)){
            //小门判断如果小于3按套计算
            if(doorArea.compareTo(new BigDecimal(SMALL_DOOR_UNIT_AREA))<0){
                priceVo.setDoorPrice(this.getTargetPrice(doorArea,skuVo.getPrice(),skuVo.getUnit()));
                priceVo.setDoorUnitPrice(skuVo.getPrice());
                priceVo.setDoorUnit(skuVo.getUnit());
            }else {
                priceVo.setDoorPrice(this.getTargetPrice(doorArea, product.getCategory().getPrice(), product.getCategory().getUnit()));
                priceVo.setDoorUnitPrice(product.getCategory().getPrice());
                priceVo.setDoorUnit(product.getCategory().getUnit());
            }
        }else{
            priceVo.setDoorPrice(this.getTargetPrice(doorArea, skuVo.getPrice(), skuVo.getUnit()));
            priceVo.setDoorUnitPrice(skuVo.getPrice());
            priceVo.setDoorUnit(skuVo.getUnit());
        }
        priceVo.setProductImage(skuVo.getImageUrl());

        List<ProductPriceVo.PartsPrice> partsPriceList = req.getPartsList().stream().map(t -> {
            ProductPriceVo.PartsPrice partsPrice = new ProductPriceVo.PartsPrice();
            partsPrice.setConfigId(t.getConfigId());
            partsPrice.setConfigName(t.getConfigName());
            if(CollectionUtils.isNotEmpty(t.getPartsArr())){
                List<ProductPriceVo.PartsPriceDetail> partsPriceDetailList = t.getPartsArr().stream().map(o -> {
                    ProductPriceVo.PartsPriceDetail detail = new ProductPriceVo.PartsPriceDetail();
                    detail.setText(o.getText());
                    detail.setValue(o.getValue());
                    AttributeParts attributeParts = this.getAttributeParts(attrParts, t.getConfigId(), o.getValue());
                    if(attributeParts!=null){
                        detail.setRemark(attributeParts.getPartRemark());
                        BigDecimal targetPrice;
                        BigDecimal partPrice = new BigDecimal(attributeParts.getPartPrice());
                        if("平方米".equals(attributeParts.getPartUnit())){
                            targetPrice=doorArea.multiply(partPrice);
                        }else if("米".equals(attributeParts.getPartUnit())){
                            Integer extraWidth=attributeParts.getAttrExtraLength()!=null?attributeParts.getAttrExtraLength():0;
                            Double railLengthTimes=attributeParts.getAttrRailLengthTimes()!=null?attributeParts.getAttrRailLengthTimes():1;
                            BigDecimal totalWidth = new BigDecimal(req.getDoorWidth() + extraWidth).multiply(new BigDecimal(railLengthTimes)).divide(new BigDecimal("100"), 2, RoundingMode.HALF_UP);
                            targetPrice=totalWidth.multiply(partPrice);
                            detail.setWidth(totalWidth);
                        }else if("个".equals(attributeParts.getPartUnit())){
                            Integer number = o.getPartInfo().getNumber()!=null?o.getPartInfo().getNumber():1;
                            targetPrice=new BigDecimal(number).multiply(partPrice);
                            detail.setNumber(number);
                        }else{
                            targetPrice= partPrice;
                        }
                        detail.setUnitPrice(partPrice);
                        detail.setUnit(attributeParts.getPartUnit());
                        detail.setPrice(targetPrice);
                    }else{
                        detail.setPrice(BigDecimal.ZERO);
                    }
                    return detail;
                }).collect(Collectors.toList());
                partsPrice.setPartsDetailList(partsPriceDetailList);
                BigDecimal totalPrice = partsPriceDetailList.stream().map(ProductPriceVo.PartsPriceDetail::getPrice).reduce(BigDecimal.ZERO, BigDecimal::add);
                partsPrice.setTotalPrice(totalPrice);
            }else{
                partsPrice.setTotalPrice(BigDecimal.ZERO);
                partsPrice.setPartsDetailList(Collections.emptyList());
            }
            return partsPrice;
        }).collect(Collectors.toList());

        priceVo.setPartsPriceList(partsPriceList);

        return priceVo;
    }


    public Long saveProductPrice(CalPriceReq req) throws Exception {
        ProductPriceVo priceVo = calProductPrice(req);
        ProdPrice prodPrice=new ProdPrice();
        prodPrice.setCustomerPhone(req.getCustomerPhone());
        prodPrice.setCustomerName(req.getCustomerName());
        prodPrice.setContent(JSON.toJSONString(priceVo));
        prodPrice.setCreateTime(new Date());
        prodPrice.setUpdateTime(new Date());
        return prodPriceService.saveOrUpdateProdPrice(prodPrice);
    }

    private AttributeParts getAttributeParts(List<AttributeParts> attrParts,Long configId,Long partsId){
       return attrParts.stream().filter(t->t.getConfigId().equals(configId) && t.getPartsId().equals(partsId)).findFirst().orElse(null);
    }

    private BigDecimal getTargetPrice(BigDecimal area,BigDecimal unitPrice,String unit){
        if("平方米".equals(unit)){
            return area.multiply(unitPrice);
        }else{
            return unitPrice;
        }
    }

    private SkuVo getSkuVo(List<SkuVo> skus,String sku,boolean isCustomerColor) {
        Optional<SkuVo> skuPrice;
        if(isCustomerColor){
           skuPrice = skus.stream().filter(t -> t.getSku().contains(sku)).findFirst();
        }else{
           skuPrice = skus.stream().filter(t -> t.getSku().equals(sku)).findFirst();
        }
        return skuPrice.orElse(null);
    }

    /**
     *
     * @param width cm
     * @param height cm
     * @return m
     */
    private BigDecimal getArea(AttributeParts ap,Integer width, Integer height) {
        //计算面积需要将宽度加上
        if(ap.getAttrExtraLength()!=null && ap.getAttrExtraLength()>0){
            width+=ap.getAttrExtraLength();
        }
        return new BigDecimal(width).multiply(new BigDecimal(height)).divide(new BigDecimal("10000"), 2, RoundingMode.HALF_UP);
    }
}
